﻿using System;
using System.Collections.Specialized;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.PowerPoint.STAMP.Properties;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Configuration;

namespace Microsoft.Office.PowerPoint.STAMP.Core
{
    [ConfigurationElementType(typeof(CustomHandlerData))]
    public class AppMessageExceptionHandler : IExceptionHandler
    {
        public AppMessageExceptionHandler(NameValueCollection ignore)
        {
        }

        public Exception HandleException(Exception exception, Guid handlingInstanceId)
        {
            ShowThreadExceptionDialog(exception, handlingInstanceId);

            EventLogWriter.WriteErrorLog(exception.ToString());

            return exception;
        }

        // Creates the error message and displays it.
        private DialogResult ShowThreadExceptionDialog(Exception ex, Guid handlingInstanceId)
        {
            string errorMsg = Resources.AppMessageExceptionHandler_ShowThreadExceptionDialog_Message + Environment.NewLine + Environment.NewLine;

            StringBuilder sb = new StringBuilder();
            StringWriter writer = new StringWriter(sb);

            AppTextExceptionFormatter formatter = new AppTextExceptionFormatter(writer, ex, handlingInstanceId);

            // Format the exception.
            formatter.Format();

            errorMsg += sb.ToString();

            return MessageBox.Show(errorMsg, Resources.AppMessageExceptionHandler_ShowThreadExceptionDialog_Header, MessageBoxButtons.OK, MessageBoxIcon.Stop);
        }
    }


    public class AppTextExceptionFormatter : TextExceptionFormatter
    {
        public AppTextExceptionFormatter(TextWriter writer, Exception exception, Guid handlingInstanceId)
            : base(writer, exception, handlingInstanceId)
        {
        }

        protected override void WriteStackTrace(string stackTrace)
        {
        }

        protected override void WriteExceptionType(Type exceptionType)
        {
            base.Indent();
            base.Writer.WriteLine("Type : {0}", exceptionType.FullName);
        }
    }

}
